/**
 * Created by Sixgod on 2016/3/17.
 */

app.factory('fileReader', ["$q", "$log", function($q, $log){
    var onLoad = function(reader, deferred, scope) {
        return function () {
            scope.$apply(function () {
                deferred.resolve(reader.result);
            });
        };
    };
    var onError = function (reader, deferred, scope) {
        return function () {
            scope.$apply(function () {
                deferred.reject(reader.result);
            });
        };
    };
    var getReader = function(deferred, scope) {
        var reader = new FileReader();
        reader.onload = onLoad(reader, deferred, scope);
        reader.onerror = onError(reader, deferred, scope);
        return reader;
    };
    var readAsDataURL = function (file, scope) {
        var deferred = $q.defer();
        var reader = getReader(deferred, scope);
        reader.readAsDataURL(file);
        return deferred.promise;
    };
    return {
        readAsDataUrl: readAsDataURL
    };
}]).
directive('fileModel', ['$parse', function ($parse) {
    return {
        restrict: 'A',
        link: function($scope, element, attrs, ngModel) {
            var model = $parse(attrs.fileModel);
            var modelSetter = model.assign;
            element.bind('change', function(event){
                $scope.$apply(function(){
                    modelSetter($scope, element[0].files[0]);
                });
                //附件预览
                $scope.file = (event.srcElement || event.target).files[0];
                $scope.getFile();
            });
        }
    };
}]).
factory('Common', [
    '$http', '$q', function($http, $q) {
        return {
            loadScript: function(url, callback) {
                var head = document.getElementsByTagName("head")[0];
                var script = document.createElement("script");
                script.setAttribute("type", "text/javascript");
                script.setAttribute("src", url);
                script.setAttribute("async", true);
                script.setAttribute("defer", true);
                head.appendChild(script);
                //fuck ie! duck type
                if (document.all) {
                    script.onreadystatechange = function() {
                        var state = this.readyState;
                        if (state === 'loaded' || state === 'complete') {
                            callback && callback();
                        }
                    }
                }
                else {
                    //firefox, chrome
                    script.onload = function() {
                        callback && callback();
                    }
                }
            },
            loadCss: function(url) {
                var ele = document.createElement('link');
                ele.href = url;
                ele.rel = 'stylesheet';
                if (ele.onload == null) {
                    ele.onload = function() {
                    };
                }
                else {
                    ele.onreadystatechange = function() {
                    };
                }
                angular.element(document.querySelector('body')).prepend(ele);
            }
        }
    }
]).
directive('ueditor', [
    'Common',
    '$rootScope',
    function(Common, $rootScope) {
        return {
            restrict: 'EA',
            require: 'ngModel',
            link: function(scope, ele, attrs, ctrl) {
                $rootScope.$emit('loading', '初始化编辑器...');//广播loading事件，可以删除
                var _self = this,
                    _initContent,
                    editor,
                    editorReady = false,
                    base = './src/ueditor/utf8-php', //ueditor目录
                    _id = attrs.ueditor;
                var editorHandler = {
                    init: function() {
                        window.UEDITOR_HOME_URL = base + '/';
                        var _self = this;
                        if (typeof UE != 'undefined') {
                            editor = UE.getEditor(_id, {
                                toolbars: [
                                    [
                                        'removeformat', '|',
                                        'fontsize','fontfamily','|',
                                        'bold', 'italic', 'forecolor','|',
                                        'ArtWord'
                                    ]
                                ]
                            });
                            editor.ready(function() {
                                editor.setHeight(500);
                                editorReady = true;
                                $rootScope.$emit('loading', '');//编辑器初始化完成
                                editor.addListener('contentChange', function() {//双向绑定
                                    if (!scope.$$phase) {
                                        scope.$apply(function() {
                                            ctrl.$setViewValue(editor.getContent());
                                        });
                                    }
                                });
                            });
                        }
                        else {
                            Common.loadScript(base + '/ueditor.config.js', null);
                            //Common.loadScript(base + '/lang/zh-cn/zh-cn.js', null);
                            Common.loadScript(base + '/ueditor.parse.min.js', null);
                            Common.loadScript(base + '/ueditor.all.js', function() {
                                Common.loadScript(base + '/addCustomizeButton.js',null);

                                _self.init();
                            });
                        }
                    },
                    setContent: function(content) {
                        if (editor && editorReady) {
                            editor.setContent(content);
                        }
                    }
                };
                ctrl.$render = function() {
                    _initContent = ctrl.$isEmpty(ctrl.$viewValue) ? '' : ctrl.$viewValue;
                    editorHandler.setContent(_initContent);//双向绑定
                };
                editorHandler.init();
                //事件
                $rootScope.$on('$routeChangeStart', function() {
                    editor && editor.destroy();
                });
            }
        }
    }
]).
directive('ac', function(){
    return {
        restrict : 'E',
        template : '<canvas id="canvas' +x+ '" width=950px height=700px class="canvas" >你的浏览器不支持canvas</canvas>',
        replace : true,
        transclude : true,
        scope:true,
        link : function(scope, element) {
            element.bind('mousedown', function(){
                scope.down();
            });
            element.bind('mouseover', function(){
                scope.over();
            });
            element.bind('mousemove', function(){
                scope.mouseDrag();
            });
            element.bind('mouseup', function(){
                scope.up();
            });
            element.bind('mouseleave', function(){
                scope.mouseLeave();
            });

        }
    };
}).
filter(
    'to_trusted', ['$sce', function ($sce) {
        return function (text) {
            return $sce.trustAsHtml(text);
        }
    }]
)
;